package com.android.utils;

import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import ma.android.app.SystemManager;

import java.text.Collator;
import java.util.Comparator;
import java.util.HashMap;

public class ShortcutNameComparator implements Comparator<ResolveInfo> {
    private Collator mCollator;
    private PackageManager mPackageManager;
    private HashMap<Object, CharSequence> mLabelCache;

    public ShortcutNameComparator() {
        mPackageManager = SystemManager.getPackageManager();
        mLabelCache = new HashMap<Object, CharSequence>();
        mCollator = Collator.getInstance();
    }

    public ShortcutNameComparator(HashMap<Object, CharSequence> labelCache) {
        mPackageManager = SystemManager.getPackageManager();
        mLabelCache = labelCache;
        mCollator = Collator.getInstance();
    }

    public final int compare(ResolveInfo a, ResolveInfo b) {
        CharSequence labelA, labelB;
        ComponentName keyA = ApkPkgUtil.getComponentNameFromResolveInfo(a);
        ComponentName keyB = ApkPkgUtil.getComponentNameFromResolveInfo(b);
        if (mLabelCache.containsKey(keyA)) {
            labelA = mLabelCache.get(keyA);
        } else {
            labelA = a.loadLabel(mPackageManager).toString().trim();
            mLabelCache.put(keyA, labelA);
        }
        if (mLabelCache.containsKey(keyB)) {
            labelB = mLabelCache.get(keyB);
        } else {
            labelB = b.loadLabel(mPackageManager).toString().trim();
            mLabelCache.put(keyB, labelB);
        }
        return mCollator.compare(labelA, labelB);
    }
};
